﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FractionFormat
{
    class FractionFormat : IFormatProvider, ICustomFormatter
    {
        // NOT FINISHED !!!
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
            {
                return this;
            }
            else
            {
                return null;
            }
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            FractionNumber fraction = arg as FractionNumber;
            if (fraction == null)
            {
                throw new FormatException(String.Format("{0} is not in the correct format!", arg));
            }
            string formatUpper = format.ToUpper();
            if (formatUpper != "N" && formatUpper != "R")
            {
                throw new FormatException(String.Format("{0} is not a correct format!", format));
            }
            if (formatUpper == "R")
            {
                return fraction.GetReal();
            }
            return fraction.GetNormal();
        }

    }

    class FractionNumber
    {
        private int numerator;
        private int denominator;

        public FractionNumber(int numerator, int denominator)
        {
            this.numerator = numerator;
            this.denominator = denominator;
        }

        public override string ToString()
        {
            return ToString("N", null);
        }

        public string ToString(string format)
        {
            return ToString(format, null);
        }

        public string ToString(IFormatProvider formatProvider)
        {
            return ToString(null, formatProvider);
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (format == null)
            {
                format = "N";
            }
            if (format == "N")
            {
                return numerator + " / " + denominator;
            }
            else
            {
                double result = (double)numerator / denominator;
                return result.ToString();
            }
        }

        internal string GetReal()
        {
            double result = (double)this.numerator / this.denominator;
            return result.ToString();
        }

        internal string GetNormal()
        {
            return this.numerator + " / " + this.denominator;
        }
    }
}
